from sqlalchemy import Column, Integer, String, Text, DateTime, JSON, Enum, ForeignKey
from sqlalchemy.orm import relationship
from .database import Base
import datetime
import enum

class TaskStatus(enum.Enum):
    """任务状态枚举"""
    PENDING = "等待中"     # 等待执行
    RUNNING = "运行中"     # 正在执行
    COMPLETED = "已完成"   # 执行完成
    FAILED = "失败"       # 执行失败
    CANCELLED = "已取消"   # 已取消

class Script(Base):
    __tablename__ = 'scripts'

    id = Column(String(36), primary_key=True)
    name = Column(String(100), unique=True, nullable=False)
    description = Column(Text)
    content = Column(Text, nullable=False)
    script_type = Column(String(50), default="Python")  # 脚本类型
    created_at = Column(DateTime, default=datetime.datetime.now)
    updated_at = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
    
    # 关联关系
    tasks = relationship("Task", back_populates="script")

    def __repr__(self):
        return f"<Script(name='{self.name}', description='{self.description}')>"

class Task(Base):
    __tablename__ = 'tasks'
    
    id = Column(String(36), primary_key=True)
    name = Column(String(100), nullable=False)
    script_id = Column(String(36), ForeignKey('scripts.id'), nullable=False)
    trigger_id = Column(String(36), nullable=True)  # 触发器ID，可为空
    params = Column(JSON, default={})
    status = Column(String(20), default=TaskStatus.PENDING.value)
    priority = Column(Integer, default=5)  # 优先级，1-10
    result = Column(JSON, nullable=True)  # 执行结果
    log = Column(Text, nullable=True)  # 执行日志
    created_at = Column(DateTime, default=datetime.datetime.now)
    updated_at = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
    start_time = Column(DateTime, nullable=True)  # 开始执行时间
    end_time = Column(DateTime, nullable=True)  # 结束执行时间
    node = Column(String(100), nullable=True)  # 执行节点
    
    # 关联关系
    script = relationship("Script", back_populates="tasks")
    
    def __repr__(self):
        return f"<Task(name='{self.name}', status='{self.status}')>"